package com.zcs.thread.communication;

/**
 * 基于volatile关键字的自己实现的信号量通信
 * @author zcs
 * @since 2023/4/21
 */
public class Signal {

    private static volatile int signal = 0;
    private static final byte[] LOCK = new byte[0];


    public static void main(String[] args) throws InterruptedException {
        new ThreadA().aVoid();
        Thread.sleep(1000);
        new ThreadB().bVoid();
    }


    static class ThreadA {

        public void aVoid() {
            new Thread(() -> {
                while (signal < 5) {
                    if (signal % 2 == 0) {
                        System.out.println("threadA: " + signal);
                        synchronized (LOCK) {
                            signal++;
                        }
                    }
                }
            }).start();
        }
    }

    static class ThreadB {
        public void bVoid() {
            new Thread(() -> {
                    while (signal < 5) {
                        if (signal % 2 == 1) {
                            System.out.println("threadB: " + signal);
                            synchronized (LOCK) {
                                signal = signal + 1;
                            }
                        }
                }
            }).start();
        }
    }
}
